import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:realm/realm.dart';

import '../../models/contract_model.dart';
import '../../services/contract_service.dart';

class ContractDetailController extends GetxController {
  final contract = Contract(
    0, // id
    '', // contractNumber
    '', // customerName
    '', // projectName
    DateTime.now(), // contractDate
    DateTime.now(), // expirationDate
    false, // isRenewed
    false, // isAbandoned
    0.0, // contractAmount
    '', // contractType
    '', // paymentMethod
    '', // paymentTerms
    '', // remarks
  ).obs;
  final isLoading = true.obs;
  late Realm realm;

  @override
  void onInit() {
    super.onInit();
    initRealm();
    loadContract();
  }

  void initRealm() {
    realm = Realm(Configuration.local([Contract.schema]));
  }

  void loadContract() {
    try {
      final id = Get.arguments['id'];
      final result = realm.find<Contract>(id);
      if (result != null) {
        contract.value = result;
      }
    } finally {
      isLoading.value = false;
    }
  }

  Future<void> handleRenew() async {
    final confirmed = await Get.dialog(
      AlertDialog(
        title: const Text('确认续约'),
        content: Text('确定要续约合同 ${contract.value.contractNumber} 吗？'),
        actions: [
          TextButton(
            onPressed: () => Get.back(result: false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Get.back(result: true),
            child: const Text('确认'),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      try {
        final service = ContractService();
        await service.handleRenew(contract.value);

        loadContract();
        Get.snackbar('续约成功', '合同 ${contract.value.contractNumber} 已成功续约');
      } catch (e) {
        Get.snackbar('续约失败', '发生错误：$e');
      }
    }
  }

  Future<void> handleAbandon() async {
    final confirmed = await Get.dialog(
      AlertDialog(
        title: const Text('确认放弃'),
        content: Text('确定要放弃合同 ${contract.value.contractNumber} 吗？'),
        actions: [
          TextButton(
            onPressed: () => Get.back(result: false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Get.back(result: true),
            child: const Text('确认'),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      try {
        final service = ContractService();
        await service.handleAbandon(contract.value);

        loadContract();
        Get.snackbar('操作成功', '合同 ${contract.value.contractNumber} 已标记为放弃');
      } catch (e) {
        Get.snackbar('操作失败', '发生错误：$e');
      }
    }
  }

  @override
  void onClose() {
    Get.delete<ContractService>();
    realm.close();
    super.onClose();
  }
}
